/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package net.jcdev.coolrss.model.dao;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import net.jcdev.coolrss.model.dao.exceptions.IllegalOrphanException;
import net.jcdev.coolrss.model.dao.exceptions.NonexistentEntityException;
import net.jcdev.coolrss.model.entity.Entry;
import net.jcdev.coolrss.model.entity.Feed;
import net.jcdev.coolrss.model.entity.Description;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author carlos
 */
public class EntryJpaController {

    public EntryJpaController() {
        emf = Persistence.createEntityManagerFactory("CoolRSSPU");
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Entry entry) {
        if (entry.getDescriptionList() == null) {
            entry.setDescriptionList(new ArrayList<Description>());
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Feed feedLink = entry.getFeedLink();
            if (feedLink != null) {
                feedLink = em.getReference(feedLink.getClass(), feedLink.getFeedLink());
                entry.setFeedLink(feedLink);
            }
            List<Description> attachedDescriptionList = new ArrayList<Description>();
            for (Description descriptionListDescriptionToAttach : entry.getDescriptionList()) {
                descriptionListDescriptionToAttach = em.getReference(descriptionListDescriptionToAttach.getClass(), descriptionListDescriptionToAttach.getDescriptionId());
                attachedDescriptionList.add(descriptionListDescriptionToAttach);
            }
            entry.setDescriptionList(attachedDescriptionList);
            em.persist(entry);
            if (feedLink != null) {
                feedLink.getEntryList().add(entry);
                feedLink = em.merge(feedLink);
            }
            for (Description descriptionListDescription : entry.getDescriptionList()) {
                Entry oldEntryIdOfDescriptionListDescription = descriptionListDescription.getEntryId();
                descriptionListDescription.setEntryId(entry);
                descriptionListDescription = em.merge(descriptionListDescription);
                if (oldEntryIdOfDescriptionListDescription != null) {
                    oldEntryIdOfDescriptionListDescription.getDescriptionList().remove(descriptionListDescription);
                    oldEntryIdOfDescriptionListDescription = em.merge(oldEntryIdOfDescriptionListDescription);
                }
            }
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Entry entry) throws IllegalOrphanException, NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Entry persistentEntry = em.find(Entry.class, entry.getEntryId());
            Feed feedLinkOld = persistentEntry.getFeedLink();
            Feed feedLinkNew = entry.getFeedLink();
            List<Description> descriptionListOld = persistentEntry.getDescriptionList();
            List<Description> descriptionListNew = entry.getDescriptionList();
            List<String> illegalOrphanMessages = null;
            for (Description descriptionListOldDescription : descriptionListOld) {
                if (!descriptionListNew.contains(descriptionListOldDescription)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain Description " + descriptionListOldDescription + " since its entryId field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            if (feedLinkNew != null) {
                feedLinkNew = em.getReference(feedLinkNew.getClass(), feedLinkNew.getFeedLink());
                entry.setFeedLink(feedLinkNew);
            }
            List<Description> attachedDescriptionListNew = new ArrayList<Description>();
            for (Description descriptionListNewDescriptionToAttach : descriptionListNew) {
                descriptionListNewDescriptionToAttach = em.getReference(descriptionListNewDescriptionToAttach.getClass(), descriptionListNewDescriptionToAttach.getDescriptionId());
                attachedDescriptionListNew.add(descriptionListNewDescriptionToAttach);
            }
            descriptionListNew = attachedDescriptionListNew;
            entry.setDescriptionList(descriptionListNew);
            entry = em.merge(entry);
            if (feedLinkOld != null && !feedLinkOld.equals(feedLinkNew)) {
                feedLinkOld.getEntryList().remove(entry);
                feedLinkOld = em.merge(feedLinkOld);
            }
            if (feedLinkNew != null && !feedLinkNew.equals(feedLinkOld)) {
                feedLinkNew.getEntryList().add(entry);
                feedLinkNew = em.merge(feedLinkNew);
            }
            for (Description descriptionListNewDescription : descriptionListNew) {
                if (!descriptionListOld.contains(descriptionListNewDescription)) {
                    Entry oldEntryIdOfDescriptionListNewDescription = descriptionListNewDescription.getEntryId();
                    descriptionListNewDescription.setEntryId(entry);
                    descriptionListNewDescription = em.merge(descriptionListNewDescription);
                    if (oldEntryIdOfDescriptionListNewDescription != null && !oldEntryIdOfDescriptionListNewDescription.equals(entry)) {
                        oldEntryIdOfDescriptionListNewDescription.getDescriptionList().remove(descriptionListNewDescription);
                        oldEntryIdOfDescriptionListNewDescription = em.merge(oldEntryIdOfDescriptionListNewDescription);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = entry.getEntryId();
                if (findEntry(id) == null) {
                    throw new NonexistentEntityException("The entry with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws IllegalOrphanException, NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Entry entry;
            try {
                entry = em.getReference(Entry.class, id);
                entry.getEntryId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The entry with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            List<Description> descriptionListOrphanCheck = entry.getDescriptionList();
            for (Description descriptionListOrphanCheckDescription : descriptionListOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Entry (" + entry + ") cannot be destroyed since the Description " + descriptionListOrphanCheckDescription + " in its descriptionList field has a non-nullable entryId field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            Feed feedLink = entry.getFeedLink();
            if (feedLink != null) {
                feedLink.getEntryList().remove(entry);
                feedLink = em.merge(feedLink);
            }
            em.remove(entry);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Entry> findEntryEntities() {
        return findEntryEntities(true, -1, -1);
    }

    public List<Entry> findEntryEntities(int maxResults, int firstResult) {
        return findEntryEntities(false, maxResults, firstResult);
    }

    private List<Entry> findEntryEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Entry.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Entry findEntry(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Entry.class, id);
        } finally {
            em.close();
        }
    }

    public int getEntryCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Entry> rt = cq.from(Entry.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }

}
